//
//  HomeTableViewController.m
//  新浪微博
//
//  Created by hbl on 16/2/14.
//  Copyright © 2016年 hbl. All rights reserved.
//

#import "HomeTableViewController.h"
#import "TitleButton.h"
#import "AFNetworking.h"
#import "AccessTool.h"
#import "UIImageView+WebCache.h"
#import "BLUser.h"
#import "BLStatus.h"
#import "MJExtension.h"
#import "BLStatusFrame.h"
#import "BLStatusCell.h"
#import "MJRefresh.h"
#import "FMDatabase.h"
#import "BLNetwork.h"
@interface HomeTableViewController ()
@property (nonatomic, strong)NSMutableArray *states;
@property (nonatomic, strong)NSArray *statesFrame;
@property (nonatomic, strong)FMDatabasePool *pool;
@end

@implementation HomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //NSString *mainPath = @"/Users/hbl/Desktop/";
    NSString *mainPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [mainPath stringByAppendingPathComponent:@"wb.sql"];
    FMDatabasePool *pool = [FMDatabasePool databasePoolWithPath:path];
    self.pool = pool;
    [pool inDatabase:^(FMDatabase *db) {
       // [db open];
        [db executeUpdate:@"create table if not EXISTS stutses (access_token text,idstr text primary key ,json blob)"];
    }];

    
    
    [self setupNavBar];
    [self setupStateData];
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self headFootRefresh];
    
}

- (void)headFootRefresh
{
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshDate)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
}

- (void)loadMore
{
    [self openSql];
    NSMutableDictionary  *dict = [NSMutableDictionary dictionary];
    Access *access = [AccessTool getTheAccess];
    dict[@"access_token"] = access.access_token;
    
    if (self.states) {
        BLStatus *tempStatus = [self.states lastObject];
        dict[@"max_id"] = @([tempStatus.idstr longLongValue] - 1);
    }
     dict[@"count"] = @(10);
    NSArray *localReslut = [self getdataFromSql:dict[@"max_id"] MinId:nil];
    if (localReslut.count) {
        NSArray *newArray = [BLStatus mj_objectArrayWithKeyValuesArray:localReslut];
        
        [self.states addObjectsFromArray:newArray];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];

    }else{

    [BLNetwork GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameter:dict
    success:^(id result) {
        NSArray *statusArray = result[@"statuses"];
        [self addstatusesToSqlWithArray:statusArray];
        [BLStatus mj_setupObjectClassInArray:^NSDictionary *{
            return  @{
                      @"pic_urls":@"BLPhoto"
                      };
        }];
        NSArray *newArray = [BLStatus mj_objectArrayWithKeyValuesArray:statusArray];
        
        [self.states addObjectsFromArray:newArray];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
        [self.pool inDatabase:^(FMDatabase *db) {
            [db close];
        }];

    } failure:^(NSError *error) {
        NSLog(@"=====失败%@",error);
        [self.tableView.mj_footer endRefreshing];
    }];
    }
    [self.tableView.mj_header endRefreshing];
    
}

- (void)setupStateData
{
    NSMutableDictionary  *dict = [NSMutableDictionary dictionary];
    Access *access = [AccessTool getTheAccess];
    dict[@"access_token"] = access.access_token;
    
    if (self.states) {
        BLStatus *tempStatus = self.states[0];
        dict[@"since_id"] = tempStatus.idstr;
    }
    
   // dict[@"count"] = @(1);
    NSArray *beginArray = [self getBeginDateFromSql];
    if (beginArray.count) {
        [BLStatus mj_setupObjectClassInArray:^NSDictionary *{
            return @{@"pic_urls":@"BLPhoto"};
        }];
        NSArray *newArray = [BLStatus mj_objectArrayWithKeyValuesArray:beginArray];
        NSMutableArray *mutableArray = [NSMutableArray array];
        [mutableArray addObjectsFromArray:newArray];
        [mutableArray addObjectsFromArray:self.states];
        self.states = mutableArray;
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self showNewStatuCount:(int)newArray.count];
    }else{
        
        [BLNetwork GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameter:dict
        success:^(id result) {
            NSArray *statusArray = result[@"statuses"];
            [self addstatusesToSqlWithArray:statusArray];
            [BLStatus mj_setupObjectClassInArray:^NSDictionary *{
                return  @{
                          @"pic_urls":@"BLPhoto"
                          };
            }];
            NSArray *newArray = [BLStatus mj_objectArrayWithKeyValuesArray:statusArray];
            NSMutableArray *mutableArray = [NSMutableArray array];
            [mutableArray addObjectsFromArray:newArray];
            [mutableArray addObjectsFromArray:self.states];
            self.states = mutableArray;
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            [self showNewStatuCount:(int)newArray.count];

        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }
}

- (void)refreshDate
{
    [self openSql];
    NSMutableDictionary  *dict = [NSMutableDictionary dictionary];
    Access *access = [AccessTool getTheAccess];
    dict[@"access_token"] = access.access_token;

    if (self.states) {
        BLStatus *tempStatus = self.states[0];
        dict[@"since_id"] = tempStatus.idstr;
    }
    
    [BLNetwork GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameter:dict
           success:^(id result) {
               NSArray *statusArray = result[@"statuses"];
               [self addstatusesToSqlWithArray:statusArray];
               [BLStatus mj_setupObjectClassInArray:^NSDictionary *{
                   return  @{
                             @"pic_urls":@"BLPhoto"
                             };
               }];
               NSArray *newArray = [BLStatus mj_objectArrayWithKeyValuesArray:statusArray];
               NSMutableArray *mutableArray = [NSMutableArray array];
               [mutableArray addObjectsFromArray:newArray];
               [mutableArray addObjectsFromArray:self.states];
               self.states = mutableArray;
               [self.tableView reloadData];
               [self.tableView.mj_header endRefreshing];
               [self showNewStatuCount:(int)newArray.count];
               
               [self.pool inDatabase:^(FMDatabase *db) {
                   [db close];
               }];
               
           } failure:^(NSError *error) {
               NSLog(@"%@",error);
               [self.tableView.mj_header endRefreshing];
           }];

    
 
}

- (void)showNewStatuCount:(int)count
{
    UIButton *newStatusBtn = [[UIButton alloc]init];
    UIImage *img = [UIImage imageNamed:@"timeline_new_status_background_os7"];
    [img resizableImageWithCapInsets:UIEdgeInsetsMake(img.size.height * 0.5, img.size.width * 0.5, img.size.height * 0.5, img.size.width * 0.5)];
    [newStatusBtn setBackgroundImage:img forState:UIControlStateNormal];
    [self.navigationController.view insertSubview:newStatusBtn belowSubview:self.navigationController.navigationBar];
    
    if (count == 0) {
        [newStatusBtn setTitle:@"没有新微博！" forState:UIControlStateNormal];
    }else{
        [newStatusBtn setTitle:[NSString stringWithFormat:@"%d条新微博",count] forState:UIControlStateNormal];
    }
    [newStatusBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    
    CGFloat mainW = [UIScreen mainScreen].bounds.size.width;
    newStatusBtn.frame = CGRectMake(0, 24,  mainW , 40);
    
    [UIView animateWithDuration:1.0 animations:^{
        newStatusBtn.transform = CGAffineTransformMakeTranslation(0, 41);
    } completion:^(BOOL finished) {
        [UIView animateKeyframesWithDuration:1 delay:1 options:UIViewKeyframeAnimationOptionCalculationModeLinear animations:^{
            newStatusBtn.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [newStatusBtn removeFromSuperview];
        }];
    }];
}



- (void)setupNavBar
{
    self.navigationItem.rightBarButtonItem = [self addBarButtonItemWithImageName:@"navigationbar_pop_os7" highlightImageName:@"navigationbar_pop_highlighted_os7" action:@selector(rightBarButtonItemClick)];
    
    self.navigationItem.leftBarButtonItem = [self addBarButtonItemWithImageName:@"navigationbar_friendsearch_os7" highlightImageName:@"navigationbar_friendsearch_highlighted_os7" action:@selector(leftBarButtonItemClick)];
    
    TitleButton *titleBtn = [[TitleButton alloc]init];
    titleBtn.bounds = CGRectMake(0, 0, 75, 45);
    [titleBtn setTitle:@"HBL" forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down_os7"] forState:UIControlStateNormal];
    self.navigationItem.titleView = titleBtn;
}

- (UIBarButtonItem *)addBarButtonItemWithImageName:(NSString *)imgName highlightImageName:(NSString *)highlightImageName action:(SEL)selecter
{
    UIButton *btn = [[UIButton alloc]init];
    [btn setBackgroundImage:[UIImage imageNamed:highlightImageName] forState:UIControlStateHighlighted];
    [btn setBackgroundImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    btn.bounds = CGRectMake(0, 0, btn.currentBackgroundImage.size.width, btn.currentBackgroundImage.size.height);
    [btn addTarget:self action:selecter forControlEvents:UIControlEventTouchUpInside];
    return [[UIBarButtonItem alloc]initWithCustomView:btn];
}


- (void)rightBarButtonItemClick
{
    NSLog(@"rightBarButtonItemClick");
}

- (void)leftBarButtonItemClick
{
    NSLog(@"leftBarButtonItemClick");
}

#pragma mark - Table view data source



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.states.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BLStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:@"status"];
    if (cell == nil) {
        cell = [[BLStatusCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"status"];
    }
    BLStatus *status = self.states[indexPath.row];
    BLStatusFrame *statusFrame = [[BLStatusFrame alloc]init];
    statusFrame.status = status;
    cell.statusFrame = statusFrame;
    cell.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BLStatus *status = self.states[indexPath.row];
    BLStatusFrame *statusFrame = [[BLStatusFrame alloc]init];
    statusFrame.status = status;
    return statusFrame.cellHight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark - sql
- (void)addstatusesToSqlWithArray:(NSArray *)statusesArray
{
    for (NSDictionary *dict in statusesArray) {
        [self addstatusesToSqlWithDict:dict];
    }
}

- (void)addstatusesToSqlWithDict:(NSDictionary *)statusesdict
{
    [self.pool inDatabase:^(FMDatabase *db) {
        Access *myAccess = [AccessTool getTheAccess];
        NSString *idstr = statusesdict[@"idstr"];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:statusesdict];
        [db executeUpdate:@"insert into stutses (access_token ,idstr ,json ) values (?,?,?)",myAccess.access_token,idstr,data];
    }];
}

- (NSArray *)getdataFromSql:(NSNumber *)maxId MinId:(NSNumber *)minId
{
    __block NSMutableArray *resultArray = nil;
    [self.pool inDatabase:^(FMDatabase *db) {
        resultArray = [NSMutableArray array];
       FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM stutses WHERE  idstr < ? ORDER BY idstr DESC LIMIT 10",maxId];
        while (resultSet.next) {
            NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:[resultSet dataForColumn:@"json"]];
            [resultArray addObject:dict];
        }
        
    }];
    
    return resultArray;
}

- (NSArray *)getBeginDateFromSql
{
    __block NSMutableArray *resultArray = nil;
    [self.pool inDatabase:^(FMDatabase *db) {
        resultArray = [NSMutableArray array];
        FMResultSet *set = [db executeQuery:@"SELECT * FROM stutses  ORDER BY idstr DESC LIMIT 20"];
        while (set.next) {
            NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:[set dataForColumn:@"json"]];
            [resultArray addObject:dict];
        }
    }];
    
    return resultArray;
}

- (void)openSql
{
    NSString *newPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:newPath]) {
        [fileManager createDirectoryAtPath:newPath withIntermediateDirectories:nil attributes:nil error:nil];
    }
    NSString *mainPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [mainPath stringByAppendingPathComponent:@"wb.sql"];
    FMDatabasePool *pool = [FMDatabasePool databasePoolWithPath:path];
    self.pool = pool;
    [pool inDatabase:^(FMDatabase *db) {
      // [db open];
        [db executeUpdate:@"create table if not EXISTS stutses (access_token text,idstr text primary key ,json blob)"];
    }];

}
@end
